package com.ziyia.androidthreadtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncTaskTest extends AppCompatActivity {
    private ProgressBar progressBar;
    private Button down;
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asynctasktest);
        progressBar = findViewById(R.id.progress);
        text = findViewById(R.id.progress_text);
    }

    public void down(View view) {
        DownLoadTask downLoadTask = new DownLoadTask();
        // 我们可以往execute()方法中传递参数，这些参数将会传递到DownLoadTask的doInBackground()方法当中
        downLoadTask.execute();
    }

    private class DownLoadTask extends AsyncTask<Object, Integer, Boolean> {
        private Integer p = 0;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setProgress(0);
        }

        @Override
        protected Boolean doInBackground(Object... objects) {
            while (true) {
                Integer downloadPercent = doDownload();
                publishProgress(downloadPercent);
                if (downloadPercent >= 100) {
                    break;
                }
            }
            return true;
        }

        private Integer doDownload() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return ++p;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            // 在这里更新下载进度
            text.setText(values[0].toString() + "/100%");
            progressBar.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            // 在这里显示下载结果。比如：下载成功 或 下载失败
            if (aBoolean) {
                Toast.makeText(AsyncTaskTest.this, "下载成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(AsyncTaskTest.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}